<template>
    <div class="app-container">
      <div class="detail-container">
        <span class="block-span" style="font-weight: bold; font-size: 18px">上海数据分中心预算调整/执行列表</span>
        <span class="block-span" style="font-size: 16px color: gray">预算项目编号： {{queryInfo.budgetProjectCode}}</span>
        <span class="block-span" style="font-size: 16px color: gray">预算大类： {{queryInfo.category}}</span>
      </div>
      <div style="display: flex; justify-content:flex-end" >
        <el-button size="mini" icon="el-icon-back" @click="returnGo">返 回</el-button>
      </div>

      <el-tabs v-model="tzDetailName" tab-position="top"  @tab-click="handleClick">
        
          <el-tab-pane label="预算调整记录" name="record">
            <div v-if="tzDetailName == 'record'" class="app-container">
            <el-table   :data="tzDetailList" @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="55" align="center" fixed/> -->
            <el-table-column type="index" width="55" fixed label="序号" align="center" />
            <el-table-column label="本预算项目编号"   fixed align="center" prop="budgetProjectCode"  width="180" >
              <template slot-scope="scope">
                <el-link type="primary" @click="handleDetail(scope.row)">{{scope.row.budgetProjectCode}}</el-link>
              </template>
            </el-table-column>
            <el-table-column label="类别（预算大类）" align="center" width="230" prop="category" show-overflow-tooltip></el-table-column>
            <el-table-column label="分类（预算子类）" align="center" prop="classify" width="230" show-overflow-tooltip></el-table-column>
            <el-table-column label="预算总金额" align="center" prop="budgetTotalAmount" show-overflow-tooltip></el-table-column>
            <el-table-column label="预算项目名称"  align="center" prop="budgetProjectName" width="180" show-overflow-tooltip/>
            <el-table-column label="执行部门"  align="center" prop="executingDepartment" width="180" show-overflow-tooltip></el-table-column>
            <el-table-column label="当前状态"  align="center" prop="approvalStatus" width="180" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="220">
                <template slot-scope="scope">
                    <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handleDetail(scope.row)"
                    >查看详情</el-button>
                </template>
            </el-table-column>
            </el-table>
            <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryCode.pageNum"
        :limit.sync="queryCode.pageSize"
        @pagination="getList"
      />
       </div>
        </el-tab-pane>
       
        

        <el-tab-pane label="预算执行记录" name="track">
          <div v-if="tzDetailName == 'track'" class="app-container">
            <el-table :data="tzDetailList" @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="55" align="center" fixed/> -->
            <el-table-column type="index" fixed width="55" label="序号" align="center" />
            <el-table-column label="本预算项目编号" fixed  align="center" prop="budgetProjectCode"  width="180" >
              <template slot-scope="scope">
                <el-link type="primary" @click="handleDetail(scope.row)">{{scope.row.budgetProjectCode}}</el-link>
              </template>
            </el-table-column>
            <el-table-column label="类别（预算大类）" align="center"  width="230" prop="category" show-overflow-tooltip></el-table-column>
            <el-table-column label="分类（预算子类）" align="center" prop="classify" width="230" show-overflow-tooltip></el-table-column>
            <el-table-column label="预算总金额" align="center" prop="budgetTotalAmount"  show-overflow-tooltip></el-table-column>
            <el-table-column label="预算项目名称"  align="center" prop="budgetProjectName" width="180"  show-overflow-tooltip/>
            <!-- <el-table-column label="备注" align="center"  prop="note" width="180"></el-table-column> -->
            <el-table-column label="执行部门"  align="center" prop="executingDepartment" width="180" show-overflow-tooltip></el-table-column>
            <el-table-column label="当前状态"  align="center" prop="approvalStatus" width="180" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="220">
                <template slot-scope="scope">
                    <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handleDetail(scope.row)"
                    >查看详情</el-button>
                </template>
            </el-table-column>
            </el-table>
            <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryCode.pageNum"
        :limit.sync="queryCode.pageSize"
        @pagination="getList"
      />
      </div>
        </el-tab-pane>
      </el-tabs>
    </div>
</template>

<script>
  import { detailProcess, listProcessGen } from "@/api/workflow/process";
  import {mergeGatherList} from '@/api/businessModule/merge.js';
  import { getEquForm } from "@/api/operations/equipment.js";
  import moment from 'moment'
  // import Parser from "@/utils/generator/parser";
  import {
    complete,
    delegate,
    transfer,
    rejectTask,
    returnList,
    returnTask,
    submitList,
    updateFormList
  } from "@/api/workflow/task";
  import { selectUser, deptTreeSelect } from "@/api/system/user";
  import ProcessViewer from "@/components/ProcessViewer";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import Treeselect from "@riophae/vue-treeselect";

  export default {
    name: "workdetail",
    components: {
      ProcessViewer,
      Treeselect
    },
    data() {
      return {
        Code: 'CODE_YS',
        queryCode: {
              pageNum: 1,
              pageSize: 10,
            budgetProjectCode: null,
            projectName:'预算调整申请'
            },
        excutionList: [],
        
        formData: {},
        tzDetailName:'record',
        title: '',
        // 遮罩层表单信息
        formLoading:true,
        // 全局loading
        fullscreenLoading: false,
        // 打印窗口
        dialogVisible: false,
        // 打印弹窗数据
        printRes: [],
        // 打印标题
        dialogTile:'打印窗口',
        // 条形码
        barCode:'',
        // 打印绑定对象
        printId: {
          id: 'printBox',
          openCallback(vue) {
            // vue.fullscreenLoading = false
          },
          //关闭打印的回调事件（无法确定点击的是确认还是取消）
          //函数中this指向当前print object对象，that返回Vue对象；
          closeCallback(vue) {
            // console.log(vue, 'vue');
            if (vue.editFlag == '0') {
              // console.log(vue,'66');
              if (Array.isArray(vue.formDisable)) {
              vue.formDisable.forEach(item => item.disableForm())
              vue.formDisable.forEach(item => item.enableWidgets('cut'))
            } else {
              vue.formDisable.disableForm()
              vue.formDisable.enableWidgets('cut')
            }

            } else {
              const vueObj = vue.formDisable.filter((item, index) => {
                return index != 0
              })
              vueObj.forEach(item => {item.disableForm()})
            }
            vue.fullscreenLoading = false
          }
        },
        objNew:{},
        // 表单数组
        formDisable:[],
        btnTitle:'通过',
        height: document.documentElement.clientHeight - 205 + "px;",
        // 模型xml数据
        loadIndex: 0,
        xmlData: undefined,
        finishedInfo: {
          finishedSequenceFlowSet: [],
          finishedTaskSet: [],
          unfinishedTaskSet: [],
          rejectedTaskSet: []
        },
        historyProcNodeList: [],
        // 部门名称
        deptName: undefined,
        // 部门树选项
        deptOptions: undefined,
        userLoading: false,
        // 用户表格数据
        userList: null,
        deptProps: {
          children: "children",
          label: "label"
        },
        // 查询参数
        queryParams: {
          deptId: undefined
        },
        total: 0,
        // 遮罩层
        loading: true,
        queryInfo: {
          category: null,
          budgetProjectCode: null
        },
        taskForm: {
          comment: "", // 意见内容
          procInsId: "", // 流程实例编号
          taskId: "", // 流程任务编号
          copyUserIds: "", // 抄送人Id
          vars: "",
          targetKey: "",
          variables:{}
        },
        // 编辑状态 0 不可编辑 1 可编辑
        editFlag: null,
        // 流程状态
        approvalStatus:null,
        rules: {
          comment: [
            { required: true, message: "请输入审批意见", trigger: "blur" }
          ]
        },
        currentUserId: null,
        variables: [], // 流程变量数据
        taskFormOpen: false,
        taskFormData: {}, // 流程变量数据
        processFormList: [], // 流程变量数据
        tzDetailList: [],
        zxDetailList: [],
        // 显示的表单
        processList:[],
        formOpen: false, // 是否加载流程变量数据
        returnTaskList: [], // 回退列表数据
        processed: false,
        returnTitle: null,
        returnOpen: false,
        rejectOpen: false,
        rejectTitle: null,
        userData: {
          title: "",
          type: "",
          open: false
        },
        copyUser: [],
        nextUser: [],
        userMultipleSelection: [],
        userDialogTitle: "",
        userOpen: false,
        businessType: null,
        // 申请编号
        serialCode: null,
        otherConfig:null,
      };
    },
    created() {
      //   this.initData();
      this.queryCode.budgetProjectCode = this.$route.query.budgetProjectCode
      this.getList()
    },
    mounted() {
        this.queryInfo.category = this.$route.query.category
        this.queryInfo.budgetProjectCode = this.$route.query.budgetProjectCode
    },
  methods: {
    handleClick(tab, event) {
        this.tzDetailName = tab.name
      if (tab.name == 'track') {
        this.queryCode.projectName = '预算执行申请'
      } else if(tab.name == 'record') {
        this.queryCode.projectName = '预算调整申请'
      }
      this.getList()
    },
      handleDetail(row) {
        console.log(row,"row");
        this.$router.push({
        path: '/workflow/process/financeformdetail/' + row.procInstId,
        query: {
          processed: false
        }
      })
      },
       
        returnGo() {
          this.$router.back(-1)
        },
      /** 查询预算调整记录 */
    getList() {
        this.loading = true
          mergeGatherList(this.queryCode, this.Code).then(response => {
          // for(let i=0;i<response.rows.length;i++){
          //   if(response.rows[i].projectName == "预算调整申请") {
            //     this.tzDetailList.push(response.rows[i])
              this.tzDetailList = response.rows
              this.total = response.total;
              this.loading = false;
          //   }else {
          //     this.zxDetailList.push(response.rows[i])
          //     this.total = response.total;
          //     this.loading = false;
          //   }
          // }

      });
      },
      // 筛选节点
      filterNode(value, data) {
        // console.log(value,data,"88890999");
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deptId = data.id;
        this.getList();
      },
      setIcon(val) {
        if (val) {
          return "el-icon-check";
        } else {
          return "el-icon-time";
        }
      },
      setColor(val) {
        if (val) {
          return "#2bc418";
        } else {
          return "#b3bdbb";
        }
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.userMultipleSelection = selection;
      },
      toggleSelection(selection) {
        if (selection && selection.length > 0) {
          this.$nextTick(() => {
            selection.forEach(item => {
              let row = this.userList.find(k => k.userId === item.userId);
              this.$refs.userTable.toggleRowSelection(row);
            });
          });
        } else {
          this.$nextTick(() => {
            this.$refs.userTable.clearSelection();
          });
        }
      },
      // 关闭标签
      handleClose(type, tag) {
        let userObj = this.userMultipleSelection.find(
          item => item.userId === tag.id
        );
        this.userMultipleSelection.splice(
          this.userMultipleSelection.indexOf(userObj),
          1
        );
        if (type === "copy") {
          // console.log(this.userMultipleSelection,"shi");
          this.copyUser = this.userMultipleSelection;
          // 设置抄送人ID
          if (this.copyUser && this.copyUser.length > 0) {
            const val = this.copyUser.map(item => item.id);
            this.taskForm.copyUserIds =
              val instanceof Array ? val.join(",") : val;
          } else {
            this.taskForm.copyUserIds = "";
          }
        } else if (type === "next") {
          this.nextUser = this.userMultipleSelection;
          // 设置抄送人ID
          if (this.nextUser && this.nextUser.length > 0) {
            const val = this.nextUser.map(item => item.id);
            this.taskForm.nextUserIds =
              val instanceof Array ? val.join(",") : val;
          } else {
            this.taskForm.nextUserIds = "";
          }
        }
      },
      /** 流程变量赋值 */
      handleCheckChange(val) {

        if (val instanceof Array) {
          this.taskForm.values = {
            approval: val.join(",")
          };
        } else {
          this.taskForm.values = {
            approval: val
          };
        }
      },
      getProcessDetails(procInsId, taskId) {
        const params = { procInsId: procInsId, taskId: taskId };
        detailProcess(params).then(res => {
          // console.log(res, "88888888");
          const data = res.data;
          this.otherConfig = data.otherConfig
          this.serialCode = data.serialCode
          this.businessType = data.businessType
          this.editFlag = data.editFlag
          // this.showFormLocalScope = data.showFormLocalScope
          this.approvalStatus = data.approvalStatus
          this.xmlData = data.bpmnXml;
          this.processFormList = data.processFormList;
          this.processList.push(data.processFormList[0])
          this.processFormList.filter(formItem => {
            if (formItem.showFormLocalScope == true) {
              return this.processList.push(formItem)
            }
          })
          this.processFormList[0].title = data.projectName
          this.taskFormOpen = data.existTaskForm;
          if (this.taskFormOpen) {
            this.taskFormData = data.taskFormData;
          }
          this.historyProcNodeList = data.historyProcNodeList;

          this.finishedInfo = data.flowViewer;
          this.formOpen = true;
          this.$nextTick(() => {
            this.formDisable = this.$refs.vFormRefSubmit
            if (this.formDisable.length > 0) {
              this.formDisable.forEach((item) => {
                item.showWidgets('serialCode')
                item.setFieldValue('serialCode',this.serialCode)
                if (data.editFlag == 0) {
                  console.log(this.$vform,'widget');
                  return [ item.disableForm(),item.enableWidgets('cut') ]
                } else {
                  item.disableWidgets('serialCode')
                }
              })
            } else {
              this.$refs.vFormRef.disableForm()
              this.$refs.vFormRef.enableWidgets('cut')
            }
            if (this.taskFormOpen) {
              this.userCheck()
            }
          })
          
          this.formLoading = false;
        });
      },
      onSelectCopyUsers() {
        this.userMultipleSelection = this.copyUser;
        this.onSelectUsers("新增抄送人", "copy");
      },
      onSelectNextUsers() {
        this.userMultipleSelection = this.nextUser;
        this.onSelectUsers("指定审批人", "next");
      },
      onSelectUsers(title, type) {
        this.userData.title = title;
        this.userData.type = type;
        this.getTreeSelect();
        this.getList();
        this.userData.open = true;
      },
      /** 通过任务 */
      async handleComplete(type,specialBtn) {
        console.log(type,"type");
        console.log(specialBtn,"spec");
        // 校验表单
        if (type == 1) {
          this.taskForm.comment = this.taskForm.comment
        } else {
          if (this.taskForm.comment == "") {
            if (specialBtn) {
            this.taskForm.comment = specialBtn
            } else {
              this.taskForm.comment = '通过'
            }
          } else {
              this.taskForm.comment = this.taskForm.comment
            }
          }

        this.taskForm.btStatus = type
        this.$refs["taskForm"].validate(async valid => {
          if (valid) {
            if (!this.taskFormOpen) {
          const res = await complete(this.taskForm)
          this.$modal.msgSuccess(res.msg);
          this.goBack();
            } else {
              this.userCheck()
            const formData = await this.$refs.vFormRefs.getFormData()
            this.taskForm.variables = formData
            const res = await complete(this.taskForm)
            this.$modal.msgSuccess(res.msg);
            this.goBack();
        }
          }
         })


      },
      async handleEnsure() {
        this.taskForm.comment = '已确认'
        if (!this.taskFormOpen) {
          const res = await complete(this.taskForm)
          this.$modal.msgSuccess(res.msg);
          this.goBack();
            } else {
              this.userCheck()
            const formData = await this.$refs.vFormRefs.getFormData()
            this.taskForm.variables = formData
            const res = await complete(this.taskForm)
            this.$modal.msgSuccess(res.msg);
            this.goBack();
        }
      },
      async handleDispose() {
        this.taskForm.comment = '处理完成'
        if (!this.taskFormOpen) {
          const res = await complete(this.taskForm)
          this.$modal.msgSuccess(res.msg);
          this.goBack();
            } else {
              this.userCheck()
            const formData = await this.$refs.vFormRefs.getFormData()
            this.taskForm.variables = formData
            const res = await complete(this.taskForm)
            this.$modal.msgSuccess(res.msg);
            this.goBack();
        }
      },
      /** 委派任务 */
      handleDelegate() {
        this.$refs["taskForm"].validate(valid => {
          if (valid) {
            this.userData.type = "delegate";
            this.userData.title = "委派任务";
            this.userData.open = true;
            this.getTreeSelect();
          }
        });
      },
      /** 转办任务 */
      handleTransfer() {
        this.$refs["taskForm"].validate(valid => {
          if (valid) {
            this.userData.type = "transfer";
            this.userData.title = "转办任务";
            this.userData.open = true;
            this.getTreeSelect();
          }
        });
      },
      /** 拒绝任务 */
      handleReject() {
         this.$refs["taskForm"].validate(valid => {
          if (valid) {
            const _this = this;
            this.$modal
              .confirm("拒绝审批单流程会终止，是否继续？")
              .then(function() {
                return rejectTask(_this.taskForm);
              })
              .then(res => {
                this.$modal.msgSuccess(res.msg);
                this.goBack();
              });
           }
        });
      },
      changeCurrentUser(val) {
        this.currentUserId = val.userId;
      },
      /** 返回页面 */
      goBack() {
        // 关闭当前标签页并返回上个页面
        this.$tab.closePage(this.$route);
        this.$router.back();
      },
      /** 提交退回任务 */
      submitReturn() {
        this.$refs["taskForm"].validate(valid => {
          if (valid) {
            if (!this.taskForm.targetKey) {
              this.$modal.msgError("请选择退回节点！");
            }
            // returnTask(this.taskForm).then(res => {
            //   this.$modal.msgSuccess(res.msg);
            //   this.goBack();
            // });
          }
        });
      }
    }
  };
</script>
  <style lang="scss" scoped>
  ::v-deep .el-dialog__body {
    height: 70vh;
    overflow-y: scroll;
  }
  .detail-container {
    margin-left: 20px;
    margin-top: 20px;
    margin-bottom: 20px;
  }
  .block-span {
    display: block;
    margin: 20px
  }
  .todoFlex {
    display: flex;
    justify-content: space-between;
  }
  .headerTitle {
    display: flex;
    justify-content: space-between;
  }
  .el-card ::v-deep .el-card__header {
    background-color: #8FC4F9;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both;
  }
  .box-Print {
    margin-top: 20px;
    // margin-bottom: 20px;
  }
  .taskPrint {
    display: flex;
    justify-content: space-between;
  }
  .box-card {
    width: 100%;
    margin-bottom: 20px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }

  .button-new-tag {
    margin-left: 10px;
  }
</style>
<style>
  @media print {
    @page {
      size:  auto;
    }
    body, html {
      height: auto !important;
    }
  }
</style>
